<template>
  <div class="feedback-page">
    <h1 class="page-title">意见反馈</h1>

    <!-- 反馈表单 -->
    <el-card class="feedback-form">
      <el-form :model="feedbackForm" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="反馈类型" prop="type">
          <el-select v-model="feedbackForm.type" placeholder="请选择反馈类型" style="width: 100%">
            <el-option label="系统问题" value="系统问题"></el-option>
            <el-option label="服务质量" value="服务质量"></el-option>
            <el-option label="意见建议" value="意见建议"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="反馈内容" prop="content">
          <el-input v-model="feedbackForm.content" type="textarea" :rows="5" placeholder="请详细描述您的意见反馈情况" maxlength="500"
            show-word-limit></el-input>
        </el-form-item>

        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="feedbackForm.contact" placeholder="请输入您的联系方式（选填）"></el-input>
        </el-form-item>

        <el-form-item class="form-actions">
          <el-button type="primary" @click="submitFeedback">提交信息</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    
    <!-- 反馈历史 -->
    <div class="feedback-history">
      <h2 class="section-title">我的反馈记录</h2>
      
      <el-card class="history-list">
        <div class="feedback-items">
          <div class="feedback-item" v-for="(feedback, index) in feedbackHistory" :key="index">
            <div class="feedback-meta">
              <div class="feedback-date">{{ formatDate(feedback.time) }}</div>
              <div class="feedback-type-tag">{{ getTypeText(feedback.type) }}</div>
            </div>
            <div class="feedback-content">
              <div class="content-text">{{ feedback.content }}</div>
              <div class="feedback-reply" v-if="feedback.reply">
                <div class="reply-header">管理层回复：</div>
                <div class="reply-content">{{ feedback.reply }}</div>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request.js'
import { getUserInfo } from '@/api/user.js'

export default {
  name: 'Feedback',
  setup() {
    const formRef = ref(null)
    const feedbackForm = ref({
      type: '',
      content: '',
      contact: ''
    })

    const rules = {
      type: [{ required: true, message: '请选择反馈类型', trigger: 'change' }],
      content: [{ required: true, message: '请输入反馈内容', trigger: 'blur' }]
    }

    const feedbackHistory = ref([
      {
        id: 1,
        type: 'system',
        content: '预约挂号完成或缴费，希望能优化及时性功能。',
        time: '2023-11-10 14:30',
        status: 'resolved',
        reply: '感谢您对疫情、我们学习和化疗系统的重视，现在可通过服务途径进行预约。'
      },
      {
        id: 2,
        type: 'service',
        content: '内核资源支持行业透明度，希望您能够随时随地获得。',
        time: '2023-11-06 09:15',
        status: 'processing',
        reply: '详情请阅读报告。'
      }
    ])

    const fetchFeedbackHistory = async () => {
      try {
        const userInfo = getUserInfo()
        if (!userInfo) {
          return
        }

        const res = await request.get('/feedback/list', {
          params: { userId: userInfo.userId }
        })

        if (res.code === 200) {
          feedbackHistory.value = res.data.map(item => ({
            id: item.feedbackId,
            type: item.type.toLowerCase(),
            content: item.content,
            time: item.commentTime,
            status: item.status === 2 ? 'resolved' : 'processing',
            reply: item.reply || ''
          })).sort((a, b) => new Date(b.time) - new Date(a.time))
        } else {
          ElMessage.error(res.message || '获取反馈记录失败')
        }
      } catch (error) {
        ElMessage.error('获取反馈记录失败: ' + (error.message || '网络错误'))
      }
    }

    onMounted(fetchFeedbackHistory)

    const formatDate = (dateString) => {
      const formattedDate = dateString.replace("T", " ").replace(/\.\d{3}\+\d{2}:\d{2}$/, "");
      return formattedDate // 实际项目中可以使用dayjs或moment格式化日期
    }

    const getTypeText = (type) => {
      switch (type) {
        case '系统频道': return '系统频道'
        case '服务质量': return '服务质量'
        case '意见建议': return '意见建议'
        case '其他': return '其他'
        default: return type
      }
    }

    const submitFeedback = async () => {
      formRef.value.validate(async (valid) => {
        if (!valid) return

        try {
          const userInfo = getUserInfo()
          if (!userInfo) {
            ElMessage.error('请先登录')
            return
          }

          const feedbackData = {
            userId: userInfo.userId,
            type: feedbackForm.value.type,
            content: feedbackForm.value.content,
            phone: feedbackForm.value.contact || ''
          }

          const res = await request.post('/feedback/add', feedbackData)
          if (res.code === 200) {
            const newFeedback = {
              id: feedbackHistory.value.length + 1,
              type: feedbackForm.value.type,
              content: feedbackForm.value.content,
              time: new Date().toLocaleString(),
              status: 'processing',
              reply: ''
            }

            feedbackHistory.value.unshift(newFeedback)
            ElMessage.success('反馈已提交，感谢您的意见！')
            resetForm()
          } else {
            ElMessage.error(res.message || '提交反馈失败')
          }
        } catch (error) {
          ElMessage.error('提交反馈失败: ' + (error.message || '网络错误'))
        }
      })
    }

    const resetForm = () => {
      formRef.value.resetFields()
    }

    return {
      formRef,
      feedbackForm,
      rules,
      feedbackHistory,
      formatDate,
      getTypeText,
      submitFeedback,
      resetForm
    }
  }
}
</script>

<style scoped>
.feedback-page {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.page-title {
  font-size: 24px;
  margin-bottom: 30px;
  color: #333;
  padding-bottom: 15px;
  text-align: left;
  font-weight: normal;
}

.feedback-form {
  margin-bottom: 30px;
  padding: 20px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.section-title {
  font-size: 18px;
  margin: 30px 0 15px;
  color: #333;
  text-align: left;
  font-weight: normal;
}

.history-list {
  margin-bottom: 30px;
  padding: 0;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.feedback-items {
  padding: 0;
}

.feedback-item {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.feedback-item:last-child {
  border-bottom: none;
}

.feedback-meta {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.feedback-date {
  color: #999;
  font-size: 14px;
  margin-right: 15px;
}

.feedback-type-tag {
  background-color: #f0f7ff;
  color: #409eff;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.feedback-content {
  margin-left: 0;
}

.content-text {
  margin-bottom: 10px;
  line-height: 1.6;
  color: #333;
}

.feedback-reply {
  background-color: #f8f8f8;
  padding: 12px;
  border-radius: 4px;
  margin-top: 10px;
}

.reply-header {
  font-weight: bold;
  margin-bottom: 5px;
  color: #666;
}

.reply-content {
  line-height: 1.6;
  color: #666;
}

.form-actions {
  margin-top: 30px;
}

.el-button {
  min-width: 100px;
}

@media (max-width: 768px) {
  .feedback-page {
    padding: 15px;
  }

  .page-title {
    font-size: 20px;
  }

  .feedback-form {
    padding: 15px;
  }

  .feedback-item {
    padding: 15px;
  }
}
</style>